package com.siwei.mes.service.laboratory.factory.material.admixtrue;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.concreteAdmixture.ConcreteAdmixtureNjsjzc;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.concreteAdmixture.DataWjjNjsj;
import com.siwei.mes.entity.laboratory.concreteAdmixture.DataWjjNjsjDetail;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.AdmixtureLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.KeyPropertyMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 外加剂-凝结时间之差
 *
 * @Description: 外加剂-凝结时间之差
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 22:08
 */
@Service
public class AdmixtureNjsjzcFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private AdmixtureLaboratoryMapper admixtureLaboratoryMapper;
    @Resource
    private KeyPropertyMapper keyPropertyMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_NJSJZC;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【外加剂-{}】", testProjectEnum.getName());
        ConcreteAdmixtureNjsjzc concreteAdmixtureNjsjzc = objJson.toJavaObject(ConcreteAdmixtureNjsjzc.class);
        if (concreteAdmixtureNjsjzc == null) {
            log.info("外加剂-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }

        DataWjjNjsj dataWjjNjsj = new DataWjjNjsj();

        dataWjjNjsj.setConclusion(NullUtils.ifNull(concreteAdmixtureNjsjzc.getCndxjl()));
        dataWjjNjsj.setS1Result(NullUtils.stringToIntRounding(concreteAdmixtureNjsjzc.getSjhntcnsjpjz()));
        dataWjjNjsj.setV1Result(NullUtils.stringToIntRounding(concreteAdmixtureNjsjzc.getSjhntznsjpjz()));
        dataWjjNjsj.setS2Result(NullUtils.stringToIntRounding(concreteAdmixtureNjsjzc.getJzhntcnsjpjz()));
        dataWjjNjsj.setV2Result(NullUtils.stringToIntRounding(concreteAdmixtureNjsjzc.getJzhntznsjpjz()));
        dataWjjNjsj.setAvgsResult(NullUtils.stringToIntRounding(concreteAdmixtureNjsjzc.getCnsjzc()));
        dataWjjNjsj.setAvgVResult(NullUtils.stringToIntRounding(concreteAdmixtureNjsjzc.getZnsjzc()));

        //存储详情数据
        List<DataWjjNjsjDetail> dataWjjNjsjDetailList = new ArrayList<>();

        List<ConcreteAdmixtureNjsjzc.NjsjzcList> njsjzcList = concreteAdmixtureNjsjzc.getNjsjzcList();
        int con = 1;
        String jcsj = null;
        for (ConcreteAdmixtureNjsjzc.NjsjzcList nj : njsjzcList) {
            if (con == 1) {
                jcsj = NullUtils.ifNull(nj.getJcrq());
                dataWjjNjsj.setS1M1(NullUtils.stringToIntRounding(nj.getSjhntddcnsj()));
                dataWjjNjsj.setS2M1(NullUtils.stringToIntRounding(nj.getJzhntddcnsj()));
                dataWjjNjsj.setS1M1Time(NullUtils.ifNullDate(nj.getSjhntjssj()));
                dataWjjNjsj.setS2M1Time(NullUtils.ifNullDate(nj.getJzhntjssj()));
                dataWjjNjsj.setV1M1(NullUtils.stringToIntRounding(nj.getSjhntddznsj()));
                dataWjjNjsj.setV2M1(NullUtils.stringToIntRounding(nj.getJzhntddznsj()));

                int xh1 = 1;
                //这里面是第一次试验的  所以GroupIndex 为 基准4  受检 1
                List<ConcreteAdmixtureNjsjzc.HntInfoList> hntInfoList = nj.getHntInfoList();
                for (ConcreteAdmixtureNjsjzc.HntInfoList hnt : hntInfoList) {
                    DataWjjNjsjDetail njsjDetail = new DataWjjNjsjDetail();
                    njsjDetail.setRecordIndex((Integer) xh1);
                    njsjDetail.setGroupIndex((Integer) 4);
                    njsjDetail.setTime(NullUtils.ifNullDate(hnt.getJzhntsj()));
                    njsjDetail.setS1(NullUtils.ifNullDouble(hnt.getJzhntgrzl()) == null ? null : NullUtils.ifNullDouble(hnt.getJzhntgrzl()) * 1000);
                    njsjDetail.setS2(NullUtils.ifNullDouble(hnt.getJzhntqd()));
                    njsjDetail.setSJMJ(NullUtils.ifNullInteger(hnt.getJzhntszmj()));

                    dataWjjNjsjDetailList.add(njsjDetail);

                    DataWjjNjsjDetail njsjDetailTwo = new DataWjjNjsjDetail();
                    njsjDetailTwo.setRecordIndex((Integer) xh1);
                    njsjDetailTwo.setGroupIndex((Integer) 1);
                    njsjDetailTwo.setTime(NullUtils.ifNullDate(hnt.getSjhntsj()));
                    njsjDetailTwo.setS1(NullUtils.ifNullDouble(hnt.getSjhntgrzl()) == null ? null : NullUtils.ifNullDouble(hnt.getSjhntgrzl()) * 1000);
                    njsjDetailTwo.setS2(NullUtils.ifNullDouble(hnt.getSjhntqd()));
                    njsjDetailTwo.setSJMJ(NullUtils.ifNullInteger(hnt.getSjhntszmj()));

                    dataWjjNjsjDetailList.add(njsjDetailTwo);

                    xh1++;
                }


            } else if (con == 2) {
                jcsj = NullUtils.ifNull(nj.getJcrq());
                dataWjjNjsj.setS1M2(NullUtils.stringToIntRounding(nj.getSjhntddcnsj()));
                dataWjjNjsj.setS2M2(NullUtils.stringToIntRounding(nj.getJzhntddcnsj()));
                dataWjjNjsj.setS1M2Time(NullUtils.ifNullDate(nj.getSjhntjssj()));
                dataWjjNjsj.setS2M2Time(NullUtils.ifNullDate(nj.getJzhntjssj()));
                dataWjjNjsj.setV1M2(NullUtils.stringToIntRounding(nj.getSjhntddznsj()));
                dataWjjNjsj.setV2M2(NullUtils.stringToIntRounding(nj.getJzhntddznsj()));

                int xh2 = 1;
                //这里面是第二次试验的  所以GroupIndex 为 基准5  受检 2
                List<ConcreteAdmixtureNjsjzc.HntInfoList> hntInfoList = nj.getHntInfoList();
                for (ConcreteAdmixtureNjsjzc.HntInfoList hnt : hntInfoList) {
                    DataWjjNjsjDetail njsjDetail = new DataWjjNjsjDetail();
                    njsjDetail.setRecordIndex((Integer) xh2);
                    njsjDetail.setGroupIndex((Integer) 5);
                    njsjDetail.setTime(NullUtils.ifNullDate(hnt.getJzhntsj()));
                    njsjDetail.setS1(NullUtils.ifNullDouble(hnt.getJzhntgrzl()) == null ? null : NullUtils.ifNullDouble(hnt.getJzhntgrzl()) * 1000);
                    njsjDetail.setS2(NullUtils.ifNullDouble(hnt.getJzhntqd()));
                    njsjDetail.setSJMJ(NullUtils.ifNullInteger(hnt.getJzhntszmj()));

                    dataWjjNjsjDetailList.add(njsjDetail);

                    DataWjjNjsjDetail njsjDetailTwo = new DataWjjNjsjDetail();
                    njsjDetailTwo.setRecordIndex((Integer) xh2);
                    njsjDetailTwo.setGroupIndex((Integer) 2);
                    njsjDetailTwo.setTime(NullUtils.ifNullDate(hnt.getSjhntsj()));
                    njsjDetailTwo.setS1(NullUtils.ifNullDouble(hnt.getSjhntgrzl()) == null ? null : NullUtils.ifNullDouble(hnt.getSjhntgrzl()) * 1000);
                    njsjDetailTwo.setS2(NullUtils.ifNullDouble(hnt.getSjhntqd()));
                    njsjDetailTwo.setSJMJ(NullUtils.ifNullInteger(hnt.getSjhntszmj()));

                    dataWjjNjsjDetailList.add(njsjDetailTwo);

                    xh2++;
                }

            } else if (con == 3) {
                jcsj = NullUtils.ifNull(nj.getJcrq());
                dataWjjNjsj.setS1M3(NullUtils.stringToIntRounding(nj.getSjhntddcnsj()));
                dataWjjNjsj.setS2M3(NullUtils.stringToIntRounding(nj.getJzhntddcnsj()));
                dataWjjNjsj.setS1M3Time(NullUtils.ifNullDate(nj.getSjhntjssj()));
                dataWjjNjsj.setS2M3Time(NullUtils.ifNullDate(nj.getJzhntjssj()));
                dataWjjNjsj.setV1M3(NullUtils.stringToIntRounding(nj.getSjhntddznsj()));
                dataWjjNjsj.setV2M3(NullUtils.stringToIntRounding(nj.getJzhntddznsj()));

                int xh3 = 1;
                //这里面是第三次试验的  所以GroupIndex 为 基准6  受检 3
                List<ConcreteAdmixtureNjsjzc.HntInfoList> hntInfoList = nj.getHntInfoList();
                for (ConcreteAdmixtureNjsjzc.HntInfoList hnt : hntInfoList) {
                    DataWjjNjsjDetail njsjDetail = new DataWjjNjsjDetail();
                    njsjDetail.setRecordIndex((Integer) xh3);
                    njsjDetail.setGroupIndex((Integer) 6);
                    njsjDetail.setTime(NullUtils.ifNullDate(hnt.getJzhntsj()));
                    njsjDetail.setS1(NullUtils.ifNullDouble(hnt.getJzhntgrzl()) == null ? null : NullUtils.ifNullDouble(hnt.getJzhntgrzl()) * 1000);
                    njsjDetail.setS2(NullUtils.ifNullDouble(hnt.getJzhntqd()));
                    njsjDetail.setSJMJ(NullUtils.ifNullInteger(hnt.getJzhntszmj()));

                    dataWjjNjsjDetailList.add(njsjDetail);

                    DataWjjNjsjDetail njsjDetailTwo = new DataWjjNjsjDetail();
                    njsjDetailTwo.setRecordIndex((Integer) xh3);
                    njsjDetailTwo.setGroupIndex((Integer) 3);
                    njsjDetailTwo.setTime(NullUtils.ifNullDate(hnt.getSjhntsj()));
                    njsjDetailTwo.setS1(NullUtils.ifNullDouble(hnt.getSjhntgrzl()) == null ? null : NullUtils.ifNullDouble(hnt.getSjhntgrzl()) * 1000);
                    njsjDetailTwo.setS2(NullUtils.ifNullDouble(hnt.getSjhntqd()));
                    njsjDetailTwo.setSJMJ(NullUtils.ifNullInteger(hnt.getSjhntszmj()));

                    dataWjjNjsjDetailList.add(njsjDetailTwo);

                    xh3++;
                }
            }
            con++;
        }

        dataWjjNjsj.setS1M1OK(true);
        dataWjjNjsj.setS1M2OK(true);
        dataWjjNjsj.setS1M3OK(true);
        dataWjjNjsj.setS2M1OK(true);
        dataWjjNjsj.setS2M2OK(true);
        dataWjjNjsj.setS2M3OK(true);

        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataWjjNjsj, "化学检测室", jcsj, detail);

        //根据样品编码查询外加剂凝结时间之差
        Map<String, Object> data_ycl_fmh_adxBySampleNo = admixtureLaboratoryMapper.findDATA_JGCL_WJJII_NJSJZCSampleNo(sampleNo);
        //查询没值说明需要  新增外加剂凝结时间之差
        if (data_ycl_fmh_adxBySampleNo == null) {
            admixtureLaboratoryMapper.addDATA_JGCL_WJJII_NJSJZC(dataWjjNjsj);
        } else {
            //修改外加剂凝结时间之差
            admixtureLaboratoryMapper.updateDATA_JGCL_WJJII_NJSJZC(dataWjjNjsj);
        }


        if (!dataWjjNjsjDetailList.isEmpty()) {
            //删除所有明细
            admixtureLaboratoryMapper.delDATA_JGCL_WJJII_NJSJZC_DETAIL(sampleNo);

            //新增所有明细
            for (DataWjjNjsjDetail det : dataWjjNjsjDetailList) {
                det.setSampleNo(sampleNo);
                String newId = keyPropertyMapper.getNewId();
                det.setId(newId);
                admixtureLaboratoryMapper.addDATA_JGCL_WJJII_NJSJZC_DETAIL(det);
            }
        }

        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            defaultUc.setConclusion(concreteAdmixtureNjsjzc.getCndxjl());
            defaultUc.setUcResultValue(concreteAdmixtureNjsjzc.getCndxjl());
            if (StringUtils.isNotBlank(concreteAdmixtureNjsjzc.getCnsjzc()) && StringUtils.isNotBlank(concreteAdmixtureNjsjzc.getZnsjzc())) {
                defaultUc.setUcTestValue("初凝:" + concreteAdmixtureNjsjzc.getCnsjzc() + ",终凝" + concreteAdmixtureNjsjzc.getZnsjzc());
            }


            //获取标准值
            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_NJSJZC.getCode())) {
                    defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                }
            }


            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_NJSJZC.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "njsjzc");
                    }
                }
            }
            //赋值
            super.setDefUc(defaultUc, experiment, "化学检测室", sampleNo, jcsj, detail);

            defaultUc.setUcParameterID(parameterID);//项目id

            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载到协会数据库：【外加剂-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        ConcreteAdmixtureNjsjzc concreteAdmixtureNjsjzc = objJson.toJavaObject(ConcreteAdmixtureNjsjzc.class);
        if (concreteAdmixtureNjsjzc == null) {
            log.info("外加剂-【{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        //根据样品编码查询矿渣粉密度
        Map<String, Object> data = admixtureLaboratoryMapper.findDATA_JGCL_WJJII_NJSJZCSampleNo(sampleNo);
        if (data == null) {
            log.info("外加剂-【{}】数据为空，跳过下载！sampleNo：{}", testProjectEnum.getName(), sampleNo);
            return null;
        }
        ConcreteAdmixtureNjsjzc.setValue(concreteAdmixtureNjsjzc, data);
        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(concreteAdmixtureNjsjzc);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data.get("AccessRuleCode")));

        experimentDetailMapper.updateByPrimaryKeySelective(detail);
        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
